package icursoft.educationms.ui.user;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lzy.okgo.callback.StringCallback;

import icursoft.educationms.BaseActivity;
import icursoft.educationms.EducationMSApplication;
import icursoft.educationms.R;
import icursoft.educationms.bean.MTalkResultBO;
import icursoft.educationms.http.HttpCallBack;
import icursoft.educationms.http.HttpResult;
import icursoft.educationms.servive.PreferencesService;
import icursoft.educationms.util.CommUtil;
import icursoft.educationms.util.Const;
import icursoft.educationms.util.MachTalkUtil;
import retrofit2.Call;
import retrofit2.Response;

public class LoginActivity extends BaseActivity {
    private Context mContext;
    private String mUser;
    private String mPassword;
    private TextView mLoginStatusMessageView;
    private EditText mUserView;
    private EditText mPasswordView;
    private View mLoginFormView;
    private View mLoginStatusView;
    Button btn_login;
    private EducationMSApplication inticareApp;
    boolean flag_username_notnull = false;
    boolean flag_pwd_notnull = false;
    int FLAG_USERNAME = 1;
    int FLAG_PWD = 2;
    LinearLayout iv_username_delete;
    LinearLayout iv_pwd_delete;
//    private SystemBarTintManager tintManager;
    private final static String TAG = LoginActivity.class.getSimpleName();

    Gson gson = new Gson();

    @Override
    public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
        super.onCreate(savedInstanceState, persistentState);
    }

    protected void setupViews() {
        mContext = this;
        mUserView = (EditText) findViewById(R.id.login_edittext_username);
        mUserView.setText(PreferencesService.getInstance(mContext).getUserPhone());
        if (!TextUtils.isEmpty(mUserView.getText().toString()))
            flag_username_notnull = true;
        mLoginStatusMessageView = (TextView) findViewById(R.id.login_status_message);
        findViewById(R.id.left_layout).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mUserView.addTextChangedListener(new EditChangedListener(FLAG_USERNAME));
        mPasswordView = (EditText) findViewById(R.id.login_edittext_password);
        mPasswordView.addTextChangedListener(new EditChangedListener(FLAG_PWD));
        btn_login = (Button) findViewById(R.id.button_login);
        // TODO: 2016/10/12 登录键背景修改
        btn_login.setBackgroundResource(R.mipmap.iv_btn_unwrite);
        btn_login.setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (checkNetwork())
                            attemptLogin();
                    }
                });
        btn_login.setClickable(false);
        iv_username_delete = (LinearLayout) findViewById(R.id.iv_username_delete);
        iv_pwd_delete = (LinearLayout) findViewById(R.id.iv_pwd_delete);
        mUserView.setOnFocusChangeListener(new View.OnFocusChangeListener() {

            @Override
            public void onFocusChange(View arg0, boolean isFocuse) {
                if (isFocuse && flag_username_notnull) {
                    iv_username_delete.setVisibility(View.VISIBLE);
                } else {
                    iv_username_delete.setVisibility(View.GONE);
                }
            }
        });
        mPasswordView.setOnFocusChangeListener(new View.OnFocusChangeListener() {

            @Override
            public void onFocusChange(View arg0, boolean isFocuse) {
                if (isFocuse && flag_pwd_notnull) {
                    iv_pwd_delete.setVisibility(View.VISIBLE);
                } else {
                    iv_pwd_delete.setVisibility(View.GONE);
                }
            }
        });
        iv_username_delete.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                mUserView.getText().clear();
            }
        });
        iv_pwd_delete.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                mPasswordView.getText().clear();
            }
        });
        mLoginFormView = findViewById(R.id.login_form);
        mLoginStatusView = findViewById(R.id.login_status);
        findViewById(R.id.btn_forget_password).setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (checkNetwork())
                            toForgotPassword();
                    }
                });
        findViewById(R.id.btn_register).setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (checkNetwork())
                            toRegister();
                    }
                });
    }

    protected void initialized() {
        mUserView.requestFocus();

        if (mUser != null) {
            mUserView.setText(mUser);
            mUserView.setSelection(mUser.length());
            flag_username_notnull = true;
            if (mUserView.isFocused() && (mUserView.getText().toString().trim().length() > 0)) {
                iv_username_delete.setVisibility(View.VISIBLE);
            } else {
                iv_username_delete.setVisibility(View.GONE);
            }
        } else {
            iv_username_delete.setVisibility(View.GONE);
        }
        if (mPassword != null && mPasswordView.isFocused()) {
            flag_pwd_notnull = true;
            mPasswordView.setText(mPassword);
            if (mPasswordView.isFocused() && (mPasswordView.getText().toString().trim().length() > 0)) {
                iv_pwd_delete.setVisibility(View.VISIBLE);
            } else {
                iv_pwd_delete.setVisibility(View.GONE);
            }
        } else {
            iv_pwd_delete.setVisibility(View.GONE);
        }

        // checkNetwork();
//        Intent intent = this.getIntent();
//        if (intent.hasExtra(Const.KEY_LOGIN_ERROR_MSG)) {
//            HiLog.i(TAG, "自动登录失败：" + intent.getStringExtra(Const.KEY_LOGIN_ERROR_MSG));
//            if (intent.getStringExtra(Const.KEY_LOGIN_ERROR_MSG).trim().length() > 0) {
//                CommUtil.showToast(mContext,
//                        intent.getStringExtra(Const.KEY_LOGIN_ERROR_MSG),
//                        Toast.LENGTH_SHORT);
//            }
//        }

        findViewById(R.id.geren).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(ImpPerInfActivity.class);
            }
        });
        findViewById(R.id.update).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(UpdatePwdActivity.class);
            }
        });


    }

    private boolean checkNetwork() {
        return CommUtil.isNetworkAvailable(mContext, true);
    }

    public void attemptLogin() {
        mUser = mUserView.getText().toString();
        mPassword = mPasswordView.getText().toString();
        boolean cancel = false;
        View focusView = null;

        if (TextUtils.isEmpty(mPassword)) {
            CommUtil.showToast(mContext, R.string.prompt_password,
                    Toast.LENGTH_SHORT);
            focusView = mPasswordView;
            cancel = true;
        }
        if (TextUtils.isEmpty(mUser)) {
            CommUtil.showToast(mContext, R.string.prompt_username_with_tip,
                    Toast.LENGTH_SHORT);
            focusView = mUserView;
            cancel = true;
        }

        if (cancel) {
            focusView.requestFocus();
        } else {
            mLoginStatusMessageView.setText(R.string.login_progress_signing_in);
            showProgress(true);
            try {
                //DataUtils.userLogin(mContext, loginCallback, mUser,mPassword);
                MachTalkUtil.userLogin(this,loginCallback, mUser, mPassword);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }


    @Override
    protected int getLayoutId() {
        return R.layout.activity_login;
    }

    private void showProgress(final boolean show) {
        int shortAnimTime = getResources().getInteger(
                android.R.integer.config_shortAnimTime);

        mLoginStatusView.setVisibility(View.VISIBLE);
        mLoginStatusView.animate().setDuration(shortAnimTime)
                .alpha(show ? 1f : 0)
                .setListener(new AnimatorListenerAdapter() {
                    @Override
                    public void onAnimationEnd(Animator animation) {
                        mLoginStatusView.setVisibility(show ? View.VISIBLE
                                : View.GONE);
                    }
                });

        mLoginFormView.setVisibility(View.VISIBLE);
        mLoginFormView.animate().setDuration(shortAnimTime)
                .alpha(show ? 0.2f : 1)
                .setListener(new AnimatorListenerAdapter() {
                    @Override
                    public void onAnimationEnd(Animator animation) {
                        // mLoginFormView.setVisibility(show ? View.GONE:
                        // View.VISIBLE);
                    }
                });
    }

    private void toForgotPassword() {
        Intent intent = new Intent(LoginActivity.this,
                ForgotPasswordActivity.class);
        this.startActivityForResult(intent, Const.REQUEST_CODE_USER_MANAGER);
    }

    public void toRegister() {
        Intent mainIntent = new Intent(LoginActivity.this,
                RegisterActivity.class);
        startActivityForResult(mainIntent, Const.REQUEST_CODE_LOGINACTIVITY);
        overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
 //       this.startActivityForResult(mainIntent, Const.REQUEST_CODE_LOGIN);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
//        if (resultCode == Const.RESULT_CODE_REGISTERACTIVITY) {
////            HiLog.i(TAG,"注册页向完善信息页跳转，登录页被关闭");
//            this.finish();
//        }
    }
    StringCallback loginCallback = new StringCallback() {
        @Override
        public void onSuccess(String str, okhttp3.Call call, okhttp3.Response response) {
            //上传成功
            Log.e("wangshu", "login==="+str);
            HttpResult param = EducationMSApplication.GSON.fromJson(str , HttpResult.class);
            if (param.getMsg() >= 0) {
                    PreferencesService.getInstance(mContext).setIsLogin(true);
                    //PreferencesService.getInstance(mContext).setUserId();
                    PreferencesService.getInstance(mContext).setUserPhone(mUserView.getText().toString());
                    PreferencesService.getInstance(mContext).setTokenLong(param.getData().toString());
            Log.e("wangshu", "TokenLong===="+ PreferencesService.getInstance(mContext).getTokenLong()+"Phone===="+PreferencesService.getInstance(mContext).getUserPhone());
//                    PreferencesService.getInstance(mContext).setTokenShort(result.getTokenShort());

//                    startActivity(new Intent(LoginActivity.this, InticareDActivity.class));
//                    overridePendingTransition(R.anim.fade, R.anim.hold);
//                    finish();
                    showProgress(false);
                } else {
                    showProgress(false);
                }
            CommUtil.showToast(mContext, param.getMsgbox().toString(),  Toast.LENGTH_SHORT);
        }
        @Override
        public void upProgress(long currentSize, long totalSize, float progress, long networkSpeed) {
            //这里回调上传进度(该回调在主线程,可以直接更新ui)
        }
    };

    @Override
    public void onClick(View view) {

    }

    class EditChangedListener implements TextWatcher {
        private CharSequence temp;// 监听前的文本
        private int editStart;// 光标开始位置
        private int editEnd;// 光标结束位置
        private final int charMaxNum = 10;
        int flag;

        public EditChangedListener(int flag) {
            super();
            this.flag = flag;

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
            temp = s;
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                                  int count) {
        }

        @Override
        public void afterTextChanged(Editable s) {

            if (temp.length() > 0) {
                if (flag == FLAG_USERNAME) {
                    flag_username_notnull = true;

                }
                if (flag == FLAG_PWD) {
                    flag_pwd_notnull = true;

                }
            } else {
                if (flag == FLAG_USERNAME) {
                    flag_username_notnull = false;

                }
                if (flag == FLAG_PWD) {
                    flag_pwd_notnull = false;

                }
            }
            if (flag_pwd_notnull && flag_username_notnull) {
                btn_login.setClickable(true);
                // TODO: 2016/10/12 设置按钮背景
                btn_login.setBackgroundResource(R.drawable.btn_three_states);
            } else {
                btn_login.setClickable(false);
                // TODO: 2016/10/12 设置按钮背景
                btn_login.setBackgroundResource(R.mipmap.iv_btn_unwrite);
            }
            if (flag_username_notnull && mUserView.isFocused()) {
                iv_username_delete.setVisibility(View.VISIBLE);
            } else {
                iv_username_delete.setVisibility(View.GONE);
            }
            if (flag_pwd_notnull && mPasswordView.isFocused()) {
                iv_pwd_delete.setVisibility(View.VISIBLE);
            } else {
                iv_pwd_delete.setVisibility(View.GONE);
            }

        }
    }
}
